package com.google.code.porntube.snap.counter;

import java.util.Date;
import java.util.logging.Level;

import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.code.porntube.snap.core.setting.Analyzer;

public final class SnapCounter {
	
	private static MemcacheService syncCache;
	
	static {
		syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
	}
	
	private static void plus(String name, int value) {
		Object counter = syncCache.get(name);
		if(counter == null)
			counter = 0;
		syncCache.put(name, ((Integer) counter) + value);
	}
	
	private static void memo(String name, Object value) {
		syncCache.put(name, value);
	}
	
	public static Object getMemo() {
		return syncCache.get(Analyzer.GLOBAL_MEMO_LAST_UPDATE);
	}
	
	public static Object getMemo(String catalog) {
		return syncCache.get(
				new StringBuffer(Analyzer.GLOBAL_MEMO_LAST_UPDATE)
					.append("_")
					.append(catalog)
					.toString()
		);
	}
	
	public static Object getCount() {
		return syncCache.get(Analyzer.GOLBAL_COUNTER_VIDEO_SNAP);
	}
	
	public static Object getCount(String catalog) {
		return syncCache.get(
				new StringBuffer(Analyzer.GOLBAL_COUNTER_VIDEO_SNAP)
					.append("_")
					.append(catalog)
					.toString()
		);
	}
	
	public static void add(String catalog) {
		Date now = new Date();
		plus(Analyzer.GOLBAL_COUNTER_VIDEO_SNAP, 1);
		plus(
				new StringBuffer(Analyzer.GOLBAL_COUNTER_VIDEO_SNAP)
					.append("_")
					.append(catalog)
					.toString(),
				1
		);
		memo(Analyzer.GLOBAL_MEMO_LAST_UPDATE, now);
		memo(
				new StringBuffer(Analyzer.GLOBAL_MEMO_LAST_UPDATE)
					.append("_")
					.append(catalog)
					.toString(),
				now
		);
	}

}
